/**
 * Created by user on 2015/9/14.
 */
angular.module('mis.lotteryManager.controllers', []).
    controller('lotteryCtrl', ['$scope', '$http', '$location', function ($scope, $http, $location) {
        var larSelect = new gObj.larSelect();
        //larSelect.paint($(".ral-list-choice"));
        $scope.currentPage = 1;
        $scope.pageSize = 10;

        //分页
        $scope.pagination = new pagination({currentPage:$scope.currentPage,pageSize: $scope.pageSize,
            url:'http://' + backOfficeHost + '/rest/v1.0/mis/lottery/lotteryList/:page/:size',
            ajax: $http,
            success:function(data){
                $scope.resultList = data.data.list;
                $scope.pageNumber = data.data.totalPage;
                $scope.count = data.data.count;
                $scope.currentPage = $(".am-active").text();
                $scope.pagination.totalPage = data.data.totalPage;
                $scope.pagination.pageHeader($scope.pageNumber);
                $('#count').text("共"+$scope.pageNumber+"页 有"+$scope.count+"数据");
            },
            error: function(err){
                //$scope.communityList = null;
            },
            params: {}
        });

        //全选列表
        $scope.allSelected = function () {
            $scope.pagination.allSelected();
        };

        //删除
        $scope.delete = function(){
            var params = {
                url: 'http://' + backOfficeHost + '/rest/v1.0/mis/lottery/lotteryDelete',
                checkObj: $(".item-check"),//checkbox对象
                key:"lotteryID",
                success: function(data){
                    var number = $(".am-active").text();//当前页码
                    $scope.pagination.selectPage(number);
                },
                error: function(err){}
            };
            $scope.pagination.listDelete(params);

        };

        var selectMenu ={
            create:function(data,select){
                for(var i in data)
                {
                    var option=data[i];
                    if(option&&option.objId&&option.communityName) {
                        var value = option.objId;
                        var text = option.communityName;
                        this.menu.append("<option value='" + value + "'>" + text + "</option>");
                    }

                }
            },
            clear:function(){
                this.menu.children().remove();
            },
            getValue:function(){
                var communities=[];
                this.menu.find("option").each(function(){
                    communities.push($(this).val());
                });
                return communities;
            }
        };

        $scope.add = function(){

            selectMenu.menu=$('#selCommunitys');

            var provinceId = $('#province_list')[0].dataset.cId;
            var cityId =  $('#city_list')[0].dataset.cId;
            var countyId = $('#county_list')[0].dataset.cId;
            var communities = selectMenu.getValue();

            if(communities.length>0){
                if(provinceId == null || cityId == null || countyId == null){
                    alert('区域信息不完整!');
                    return;
                };
            };

            if(countyId){
                if(provinceId == null || cityId == null){
                    alert('区域信息不完整!');
                    return;
                };
            };

            if(cityId){
                if(provinceId == null){
                    alert('区域信息不完整!');
                    return;
                };
            };


            var opt = {
                provinceId : provinceId,
                cityId : cityId,
                countyId :countyId,
                communities: communities,
                isValid: true
            }

            console.debug(opt);


        };

        //级联框
        var cascadData = {
            provinceUrl: 'http://' + backOfficeHost + '/rest/v1.0/backoffice/region/regionPrivince',
            cityUrl: 'http://' + backOfficeHost + '/rest/v1.0/backoffice/region/regionCity',
            cityAreaUrl: 'http://' + backOfficeHost + '/rest/v1.0/backoffice/region/regionCounty',
            villageUrl: 'http://' + backOfficeHost + '/rest/v1.0/mis/community/communityList',
            ajax: $http
        };
        $scope.cascading = new gObj.cascading(cascadData);
        $scope.cascading.paint($(".city-cascading")[0],false, 'list');

        //过滤小区
        $scope.cnameFilter = function(name){

            if(name.length <2 && name.length>0){
                return;
            }

            var html = "";

            var countyId = $('#county_list')[0].dataset.cId;
            var cname = $scope.cname;

            var opt = {
                countyId : countyId,
                communityName : cname,
                isValid: true
            };
            console.debug(opt);
            $http.post('http://' + backOfficeHost + '/rest/v1.0/mis/community/communityList', opt, {
                headers: {'Content-Type': 'application/json;charset=utf-8'}
            }).success(function (data) {
                console.debug(data);
                $scope.communityList = data.data.list;

                $(document).on("dblclick","#communities_select option",function(){
                    $(this).appendTo('#selCommunitys');
                });
                $(document).on("dblclick","#selCommunitys option",function(){
                    $(this).appendTo('#communities_select');
                });

            }).error(function () {
            });

        };

        //全部移到右边
        $scope.addAllCommunity = function () {
            //获取全部的选项,删除并追加给对方
            $('#communities_select option').appendTo('#selCommunitys');
            $scope.commList = [];
        };

        //全部移到左边
        $scope.removeAllCommunity = function () {
            var selectedCom = $('#selCommunitys option');
            for(var i = 0;i < selectedCom.length;i++){
                var item = {objId:selectedCom[i].value,communityName:selectedCom[i].label};
                $scope.commList.push(item);
            }

            $('#selCommunitys option').appendTo('#communities_select');
        };
        //移到右边
        $scope.addCommunity = function () {
            var selectedCom = $('#communities_select option:selected');
            for(var i = 0;i < selectedCom.length;i++){
                for(var j in $scope.commList){
                    if(selectedCom[i].value == $scope.commList[j].objId)$scope.commList.splice(j,1);
                }
            }
            //先判断是否有选中
            if (!$("#communities_select option").is(":selected")) {
                alert("请选择需要移动的选项")
            }
            //获取选中的选项，删除并追加给对方
            else {
                $('#communities_select option:selected').appendTo('#selCommunitys');
            }
        };

        //移到左边
        $scope.removeCommunity = function () {
            var selectedCom = $('#selCommunitys option:selected');
            for(var i = 0;i < selectedCom.length;i++){
                var item = {objId:selectedCom[i].value,communityName:selectedCom[i].label};
                $scope.commList.push(item);
            }
            //先判断是否有选中
            if (!$("#selCommunitys option").is(":selected")) {
                alert("请选择需要移动的选项")
            }
            else {
                $('#selCommunitys option:selected').appendTo('#communities_select');
            }
        };

        $scope.editPrize = function (lotteryId) {
            $location.path('/lotteryPrizeList/' + lotteryId);
        }


    }]).controller('lotteryPrizeCtrl', ['$scope', '$http', '$location',  '$routeParams', function ($scope, $http, $location, $routeParams) {

        var larSelect = new gObj.larSelect();
        //larSelect.paint($(".ral-list-choice"));
        $scope.currentPage = 1;
        $scope.pageSize = 10;

        //分页
        $scope.pagination = new pagination({currentPage:$scope.currentPage,pageSize: $scope.pageSize,
            url:'http://' + backOfficeHost + '/rest/v1.0/mis/lottery/getPrizeByLotteryId/:page/:size',
            ajax: $http,
            success:function(data){
                $scope.resultList = data.data.list;
                $scope.pageNumber = data.data.totalPage;
                $scope.count = data.data.count;
                $scope.currentPage = $(".am-active").text();
                $scope.pagination.totalPage = data.data.totalPage;
                $scope.pagination.pageHeader($scope.pageNumber);
                $('#count').text("共"+$scope.pageNumber+"页 有"+$scope.count+"数据");
            },
            error: function(err){
                //$scope.communityList = null;
            },
            params: {lotteryId :  $routeParams.lotteryId}
        });

        //全选列表
        $scope.allSelected = function () {
            $scope.pagination.allSelected();
        };

        //加载下拉列表
        var params = {};
        $http.post('http://' + backOfficeHost + '/rest/v1.0/backoffice/lottery/getAllProduct', params, {
            headers: {'Content-Type': 'application/json;charset=utf-8'}
        }).success(function (data) {
            var productList = new Array();
            for (var i = 0; i < data.data.length; i++) {
                productList.push({value: data.data[i].id, name: data.data[i].name});
            }
            $scope.productList = productList;
        }).error(function () {
        });


        $scope.selectFile = function (files) {
            $scope.image = files[0]
        };

        $scope.add = function () {

            var fd = new FormData();
            if ($scope.image != null)
            fd.append('image1', $scope.image);
            fd.append('productId', $('#productId').val());
            fd.append('levelName', $scope.levelName);
            fd.append('prizeCount', $scope.prizeCount);
            fd.append('rewardCount', $scope.rewardCount);
            fd.append('prizeLevel', $scope.prizeLevel);
            fd.append('lotteryId', $routeParams.lotteryId);
            fd.append('prizePosition', $scope.prizePosition);
            fd.append('prizeProbability', $scope.prizeProbability);


            $http.post('http://' + backOfficeHost + '/rest/v1.0/backoffice/lottery/addPrize', fd, {
                transformRequest: angular.identity,
                headers: {'Content-Type': undefined}
            }).success(function () {
                $scope.pagination.selectPage(1);//插入成功显示第一页
                $('#doc-modal-add').modal("close");
                if(data.result.status == 1){
                    alert("新增成功！");
                    $scope.addData = {};

                }else{
                    alert("新增失败！");
                }

            }).error(function () {
            });
        }


        $scope.delete = function (prizeId) {
            //var params = {
            //    prizeId: prizeId
            //}
            //$http.post('http://' + backOfficeHost + '/rest/v1.0/backoffice/lottery/deletePrize', params, {
            //    headers: {'Content-Type': 'application/json;charset=utf-8'}
            //}).success(function () {
            //    $scope.filter();
            //});

            var params = {
                url: 'http://' + backOfficeHost + '/rest/v1.0/mis/lottery/deleteLotteryPrize',
                checkObj: $(".item-check"),//checkbox对象
                key:"LotteryPrizeID",
                success: function(data){
                    var number = $(".am-active").text();//当前页码
                    $scope.pagination.selectPage(number);
                },
                error: function(err){}
            };
            $scope.pagination.listDelete(params);
        }

        $scope.back = function () {
            $location.path('/lotteryList');
        };


        $scope.updateShow = function(data,index){
            $("#productId_Edit"+index).val(data.product_id.toString());
        };

        //编辑
        $scope.update = function(updateData,index){
            var lData = {lotteryPrizeID:"",lotteryPrize:{}};
            if(updateData.id)lData.lotteryPrizeID = Number(updateData.id);
            if(updateData.product_id)lData.product_id = updateData.product_id;
            if(updateData.level_name)lData.level_name = updateData.level_name;
            if(updateData.prize_count)lData.prize_count = Number(updateData.prize_count);
            if(updateData.reward_count)lData.reward_count = updateData.reward_count;
            if(updateData.prize_level)lData.prize_level = updateData.prize_level;
            if(updateData.prize_position)lData.prize_position = updateData.prize_position;
            if(updateData.prize_probability)lData.prize_probability = updateData.prize_probability;
            //uData.user.roleID = $scope.getSelectedRole($(obj.parentNode.parentNode).find(".lists_selected option"));
            //uData = deleteObjNull(uData);
            var params = {
                url: 'http://' + backOfficeHost + '/rest/v1.0/mis/lottery/lotteryPrizeEdit',
                updateData: lData,
                success: function(data){
                    var number = $(".am-active").text();//当前页码
                    $scope.pagination.selectPage(number);

                    if(data.result.status == 1){
                        $('#doc-modal-'+index).modal("close");
                        alert("修改成功！");
                    }else {
                        $('#doc-modal-'+index).modal("close");
                        alert("修改失败！");
                    }
                },
                error: function(){
                    $('#doc-modal-'+index).modal("close");
                    alert("修改失败！");
                }
            };
            $scope.pagination.listUpdate(params);
        };


    }])




;
